import csv
import os
from collections import defaultdict
from datetime import datetime
from multi_online.config import MinSpeed


def get_hourly_indices(datetime_list):
    hourly_indices = []
    for index, dt in enumerate(datetime_list):
        if dt.minute == 0 and dt.second == 0:
            hourly_indices.append(index)
        elif dt.minute == 30 and dt.second == 0:
            hourly_indices.append(index)
    return hourly_indices


def format_conversion(original_dict):
    # 创建一个默认字典，用来存储转换后的结果，这里使用列表而不是集合以保持顺序
    transformed_dict = defaultdict(list)
    # 遍历原始字典，填充转换后的字典
    for key, value_list in original_dict.items():
        for value in value_list:
            transformed_dict[value].append(key)
    # 将defaultdict转换为普通字典
    result_dict = {k: v for k, v in transformed_dict.items()}

    return result_dict


def get_type_pass_time():
    dd = {
        "10001": {
            "1": 2,
            "2": 2,
            "3": 2,
            "8": 2,
            "10": 2
        },
        "10002": {
            "1": 2,
            "2": 2,
            "3": 2,
            "8": 2,
            "10": 2
        },
        "10003": {
            "1": 3,
            "2": 3,
            "3": 3,
            "8": 3,
            "10": 3
        },
        "10005": {
            "1": 1.8,
            "2": 1.8,
            "3": 1.8,
            "8": 1.8,
            "10": 1.8
        },
        "10006": {
            "1": 2.5,
            "2": 2.5,
            "3": 2.5,
            "8": 2.5,
            "10": 2.5
        }
    }
    return dd


def get_pass_time(dist):
    car = MinSpeed["car"]
    bus = MinSpeed["bus"]
    truck = MinSpeed["truck"]
    # 不同车型通行期望时间（分钟）
    car_pass_time = round((dist / car * 60), 2)
    bus_pass_time = round((dist / bus * 60), 2)
    truck_pass_time = round((dist / truck * 60), 2)
    # other_time = round((dist / car * 60), 2)
    pass_time_dict = {
        "1": car_pass_time,
        "2": truck_pass_time,
        "3": bus_pass_time,
        "8": truck_pass_time,
        "10": car_pass_time,
        "0": car_pass_time
    }

    return pass_time_dict


def get_latest_folder(base_dir):
    # 获取所有子文件夹的列表
    folders = [f for f in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, f))]
    # 过滤并解析符合时间戳格式的文件夹名
    timestamp_folders = {}
    for folder in folders:
        try:
            timestamp = datetime.strptime(folder, "%Y-%m-%d_%H-%M-%S")
            timestamp_folders[timestamp] = folder
        except ValueError:
            # 如果文件夹名不符合时间戳格式，则跳过
            continue

    if not timestamp_folders:
        print("没有找到符合时间戳格式的文件夹")
        return None

    # 找到最新的时间戳对应的文件夹
    latest_timestamp = max(timestamp_folders.keys())
    latest_folder = timestamp_folders[latest_timestamp]

    return os.path.join(base_dir, latest_folder)


def append_to_csv(file_path, row_data):
    """
    向CSV文件中追加一行数据。

    :param file_path: CSV文件的路径
    :param row_data: 要追加的数据行，作为列表或元组传递
    """
    # 打开CSV文件，使用'a'模式表示追加（append）
    with open(file_path, mode='a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        # 写入一行数据
        writer.writerow(row_data)


if __name__ == '__main__':
    dist_dict = {}


